/**
 * 用户登录注册
 */
var mongoose = require('mongoose');

var User = mongoose.model('User');

// 用户登录API（POST请求）
exports.login = function (req, res) {

    var username = req.body.username; // 用户名
    var password = req.body.password; // 密码

    // 查询用户表
    User.findOne({
        username: username
    }, function (err, docs) {
        if (err) {
            res.json({
                "status": "error",
                "msg": "error_system"
            });
        } else if (docs == null) {
            res.json({
                "status": "error",
                "msg": "error_username"
            });
        } else {
            if (docs.password == password) {
                res.json({
                    "status": "success",
                    "msg": ""
                });
            } else {
                res.json({
                    "status": "error",
                    "msg": "error_password"
                });
            }
        }
    })
}

// 用户注册API
exports.register = function (req, res) {
    var username = req.body.username;
    var password = req.body.password;

    // 是否已注册
    User.findOne({
        username: username
    }, function (err, docs) {
        if (err) {
            res.json({
                "status": "error",
                "msg": "error_system"
            }); 
        } 
        // 未注册
        else if (docs == null) {
           
            var newUser = new User({
                username: username,
                password: password
            });
            
            // 存入数据库
            newUser.save(function (err) {
                if (err) {
                    res.json({
                        "status": "error",
                        "msg": "error_system"
                    });
                } else {
                    res.json({
                        "status": "success",
                        "msg": ""
                    });
                }
            });
        } 
        // 已注册
        else {
            res.json({
                "status": "error",
                "msg": "user_exist"
            });
        }
    })
}